package com.sky.controller.user;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaIgnore;
import com.sky.dto.CreatingUserDTO;
import com.sky.dto.EmailCreatingUserDTO;
import com.sky.dto.LoginDTO;
import com.sky.properties.JwtProperties;
import com.sky.result.Result;
import com.sky.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 用户认证相关接口
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserAuthController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 用户申请创建账号时邮箱验证
     *
     * @param creatingUserDTO 用户创建账号表单
     */
    @SaIgnore
    @PostMapping("/creatingUserEmail")
    public Result creatingUserEmail(@RequestBody CreatingUserDTO creatingUserDTO) throws Exception {
        log.info("用户申请创建账号时邮箱验证:{}", creatingUserDTO);
        userService.creatingUserEmail(creatingUserDTO);
        return Result.success();
    }

    /**
     * 创建用户
     *
     * @param emailCreatingUserDTO 用户创建后端加密信息
     */
    @SaIgnore
    @PostMapping("/creatingUser")
    public Result creatingUser(@RequestBody EmailCreatingUserDTO emailCreatingUserDTO) throws Exception {
        log.info("用户创建:{}", emailCreatingUserDTO);
        userService.creatingUser(emailCreatingUserDTO);
        return Result.success();
    }

    /**
     * 用户登录
     *
     * @param loginDTO 登录表单
     * @return userToken
     */
    @SaIgnore
    @PostMapping("/login")
    public Result userLogin(@RequestBody LoginDTO loginDTO) {
        log.info("用户登录:{}", loginDTO);
        String token = userService.userLogin(loginDTO);
        return Result.success(token);
    }

    /**
     * 用户退出登录
     *
     * @return Result
     */
    @SaCheckLogin
    @PostMapping("/logout")
    public Result logout(@RequestHeader(value = "${sky.jwt.user-token-name}", required = false) String token) {
        userService.userLogout(token);
        return Result.success();
    }
} 